package csc.fresher.view;

import java.io.IOException;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import csc.fresher.commons.BankingConstant;
import csc.fresher.dao.DepositAccountDao;
import csc.fresher.entity.AccountState;
import csc.fresher.entity.AccountTransactionState;
import csc.fresher.entity.CustomerAccount;
import csc.fresher.entity.CustomerAccountOverall;
import csc.fresher.entity.DepositAccount;
import csc.fresher.entity.SavingAccount;
import csc.fresher.entity.SystemUser;
import csc.fresher.service.AccountService;
import csc.fresher.service.CurrencyService;
import csc.fresher.service.DepositAccountService;
import csc.fresher.service.SystemUserService;

@Component
@Scope("session")
public class AddDepositOrSavingAccount implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Autowired
	AccountService accountService;
	
	@Autowired
	private DepositAccountService depositManageService;

	@Autowired
	private SystemLoginManageBean systemLoginManageBean;

	@Autowired
	private SystemUserService systemUserService;

	@Autowired
	private CurrencyService currencyServices;
	
	private String selectSearchType;
	private List<CustomerAccountOverall> savingAccountList;
	private String searchValue;
	private DataModel<CustomerAccountOverall> savingAccountListDataModel;
	private CustomerAccountOverall customerAccountOverall;
	private String accountBalance;
	private String accountType;
	private  String username;
	private  String password;
	private final String idCardNumber_pattern = "^\\s*\\d+\\s*$";
	private final String balance_pattern = "^\\s*\\d+\\s*$"; 
	private  Pattern pattern;
	private  Matcher matcher;
	private  String idCardNumberStatus;
	private  String balanceStatus;
	private String idCardNumber;
	private String currency;


	private String showCurrency;
	public void onLoad() {
//		SystemUser systemUser;
//
//		if (systemLoginManageBean.getSystemUser() == null) {
//			try {
//				FacesContext.getCurrentInstance().getExternalContext()
//						.redirect("/csc_final/templates3/Logon.jsf");
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		} else {
//			systemUser = systemLoginManageBean.getSystemUser();
//			List<Long> listrole = systemUserService
//					.getRoleByUserName(systemUser.getUserName());
//			boolean result = checkRole(listrole);
//			if (result == false) {
//				try {
//					FacesContext.getCurrentInstance().getExternalContext()
//							.redirect("/csc_final/templates3/Logon.jsf");
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//		}
	}

	public boolean checkRole(List<Long> listRole) {

		for (int i = 0; i < listRole.size(); i++) {
			if (3 == listRole.get(i) || 4 == listRole.get(i)) {
				return true;
			}
		}
		return false;
	}
	@PostConstruct
	public void init() {
	
		this.savingAccountListDataModel = null;
				

	}

	// search button
	public String search() {
		
		if(checkSearchValue(searchValue)){
			if ("idCardNumber".equals(selectSearchType)) {
				try{
					if(checkIdCardNumber(searchValue)){
						long idCard = Long.parseLong(searchValue);
						savingAccountList = depositManageService.getAllAccountByIDCardNumber(idCard);
						savingAccountListDataModel = new ListDataModel<CustomerAccountOverall>(savingAccountList);
					}
					
				}catch(Exception e){
					e.printStackTrace();
				}
				
				} 
				
		}
	
		return "SearchAccountByIDCard";
	}

	// edit button
	public String addNew() {
		
//		customerAccountOverall = savingAccountListDataModel.getRowData();
		return "AddDepositOrSavingAccount";
	}

	public String submit(){
		try{
		long CustomerId = 0L;
		for(CustomerAccountOverall cusAcc : savingAccountList){
			CustomerId = cusAcc.getCustomerID();
		}
		if ("deposit".equals(accountType)) {
			DepositAccount depositAccount = new DepositAccount();
			depositAccount.setAccountBalance(Double
					.parseDouble(accountBalance));
			depositAccount
					.setAccountType(BankingConstant.ACCOUNT_TYPE_DEPOSIT);
			depositAccount.setAccountState(AccountState.NEW);
			depositAccount.setRepeatable(false);
			depositAccount.setCreatedDate(new Timestamp(System
					.currentTimeMillis()));
			depositAccount.setCustomerID(CustomerId);
			depositAccount
					.setAccountTransactionState(AccountTransactionState.NEW);
			long depositNewNumber = accountService.createDepositAccount(depositAccount);
			if(depositNewNumber > 0) {
				return "DepositAccountManagement";
			} else {
				return "Error";
			}
		} else if ("saving".equals(accountType)) {
			SavingAccount savingAccount = new SavingAccount();
			savingAccount.setAccountBalance(Double
					.parseDouble(accountBalance));
			savingAccount
					.setAccountType(BankingConstant.ACCOUNT_TYPE_DEPOSIT);
			savingAccount.setAccountState(AccountState.NEW);
			savingAccount.setRepeatable(false);
			savingAccount.setCreatedDate(new Timestamp(System
					.currentTimeMillis()));
			savingAccount.setCustomerID(CustomerId);
			savingAccount
					.setAccountTransactionState(AccountTransactionState.NEW);
			if(currency.equals("usd")){
				savingAccount.setCurrencyID(1);
			}else if(currency.equals("vnd")){
				savingAccount.setCurrencyID(2);
			}
			
			long savingNewNumber = accountService.createSavingAccount(savingAccount);
			if(savingNewNumber > 0) {
				return "SavingAccountManagement";
			} else {
				return "Error";
			}
		}
		}catch(Exception e){
			e.printStackTrace();
		}
		return "Error";
	}

	public void showCurrency(ValueChangeEvent ex){
		
		if(ex.getNewValue().toString().equals("saving")){
			
			showCurrency = "show";
		}else if(ex.getNewValue().toString().equals("deposit")){
			
			showCurrency = "hide";
		}else{
			showCurrency = "hide";
		}
	}
	
	public String getSelectSearchType() {
		return selectSearchType;
	}

	public void setSelectSearchType(String selectSearchType) {
		this.selectSearchType = selectSearchType;
	}

	public List<CustomerAccountOverall> getDepositAccountList() {
		return savingAccountList;
	}

	public void setDepositAccountList(
			List<CustomerAccountOverall> depositAccountList) {
		this.savingAccountList = depositAccountList;
	}

	public String getSearchValue() {
		return searchValue;
	}

	public void setSearchValue(String searchValue) {
		this.searchValue = searchValue;
	}

	public DataModel<CustomerAccountOverall> getSavingAccountListDataModel() {
		return savingAccountListDataModel;
	}

	public void setSavingAccountListDataModel(
			DataModel<CustomerAccountOverall> depositAccountListDataModel) {
		this.savingAccountListDataModel = depositAccountListDataModel;
	}

	public CustomerAccountOverall getCustomerAccountOverall() {
		return customerAccountOverall;
	}

	public void setCustomerAccountOverall(CustomerAccountOverall customerAccount) {
		this.customerAccountOverall = customerAccount;
	}
	
	
	public String getAccountType() {
		return accountType;
	}

	public void setAccountType(String accountType) {
		this.accountType = accountType;
	}



	public  String getUsername() {
		return username;
	}

	public  void setUsername(String username) {
		this.username = username;
	}

	public  String getPassword() {
		return password;
	}

	public  void setPassword(String password) {
		this.password = password;
	}

	public boolean checkIdCardNumber(String idCardNumber) {

		pattern = Pattern.compile(idCardNumber_pattern);
		matcher = pattern.matcher(idCardNumber);
		return matcher.matches();

	}

	public boolean checkBalance(String balance) {

		pattern = Pattern.compile(balance_pattern);
		matcher = pattern.matcher(balance);
		return matcher.matches();
	}

	public String getAccountBalance() {
		return accountBalance;
	}

	public void setAccountBalance(String accountBalance) {
		this.accountBalance = accountBalance;
	}

	public String getIdCardNumber() {
		if (checkBalance(accountBalance)) {
			balanceStatus = "";
		} else {
			balanceStatus = "<span style='color:red; margin-left:10px'><b> Invalid Balance!</b></span>";
		}
		return idCardNumber;
	}

	public void setIdCardNumber(String idCardNumber) {
		if (checkIdCardNumber(idCardNumber) ) {
			idCardNumberStatus = "";
		} else {
			idCardNumberStatus = "<span style='color:red; margin-left:10px'><b> Invalid ID Card Number Or This ID have been existed!</b></span>";
		}
		this.idCardNumber = idCardNumber;
	}

	public String getIdCardNumberStatus() {
		return idCardNumberStatus;
	}

	public void setIdCardNumberStatus(String idCardNumberStatus) {
		this.idCardNumberStatus = idCardNumberStatus;
	}

	public String getBalanceStatus() {
		return balanceStatus;
	}

	public void setBalanceStatus(String balanceStatus) {
		this.balanceStatus = balanceStatus;
	}

	public String getShowCurrency() {
		return showCurrency;
	}

	public void setShowCurrency(String showCurrency) {
		this.showCurrency = showCurrency;
	}
	
	public String getCurrency() {
		return currency;
	}

	public void setCurrency(String currency) {
		this.currency = currency;
	}
	
	public boolean checkSearchValue(String searchValue){
		boolean result = false;
		try {
		if(null == searchValue || searchValue == "" || "".equals(searchValue) || searchValue.isEmpty()){
			result = false;
		}else{
			result = true;
		}
		}catch(Exception e){
			e.printStackTrace();
		}
		return result;
	}

}
